import { useEffect, useState } from 'react'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { useGraphicStore } from '@/stores/audio'
import { audioService, AudioResponse } from '@/services'
import { downloadFile } from '@/lib/download'
import { useGlobalMethods } from '@/hooks/useGlobalMethods'
import { cn } from '@/lib/utils'

const defPrompt = ''

const PhotoUploadLayout = ({
  commit,
  formSectionParams,
  children,
}: {
  commit: (data: AudioResponse) => void
  formSectionParams: any
  children: React.ReactNode
}) => {
  const { handlePreview } = useGlobalMethods()
  const {
    fetchSystemConfig,
    systemConfig,
    pictureList,
    setPictureList,
    setCreatedId,
  } = useGraphicStore()
  const [formErrors, setFormErrors] = useState({
    pictureType: '',
    pictureStyle: '',
    officalAccountOrientation: '',
    content: '',
    submit: '',
  })
  const [formInfo, setFormInfo] = useState({
    pictureType: '',
    pictureStyle: '',
    officalAccountOrientation: '',
    // content: '东方美女，长发，全身',
    content: defPrompt,
  })
  useEffect(() => {
    fetchSystemConfig()
  }, [fetchSystemConfig])

  useEffect(() => {
    return () => {
      setPictureList([])
    }
  }, [])

  useEffect(() => {
    if (formSectionParams?.id) {
      const item = formSectionParams
      // 回写数据
      setFormInfo({
        pictureType: item.pictureType + '',
        pictureStyle: item.pictureStyle + '',
        officalAccountOrientation: item.officalAccountOrientation + '',
        content: item.keywords,
      })
      if (item?.graphic_creation_offical_account_pictures?.length > 0) {
        const pictureList =
          item.graphic_creation_offical_account_pictures[0]?.result?.data ?? []

        pictureList.forEach((picItem: any) => {
          picItem.parentId = item.graphic_creation_offical_account_pictures[0]?.id
        })
        const textId = item.graphic_creation_offical_account_texts[0]?.id + ''

        setCreatedId(textId)

        setPictureList(pictureList)
      }
    }
  }, [formSectionParams, setCreatedId, setPictureList])

  const validateForm = () => {
    const errors = {
      pictureType: '',
      pictureStyle: '',
      officalAccountOrientation: '',
      content: '',
      submit: '',
    }
    let isValid = true

    if (!formInfo.pictureType) {
      errors.pictureType = 'Profiling'
      isValid = false
    }
    if (!formInfo.officalAccountOrientation) {
      errors.officalAccountOrientation = 'Type'
      isValid = false
    }
    if (!formInfo.pictureStyle) {
      errors.pictureStyle = 'Style'
      isValid = false
    }
    if (!formInfo.content.trim()) {
      errors.content = 'Please enter the key information for the copy'
      isValid = false
    }

    setFormErrors(errors)
    return isValid
  }

  const clearError = (field: string) => {
    setFormErrors((prev) => ({
      ...prev,
      [field]: '',
      submit: '',
    }))
  }

  const handleSubmit = async () => {
    if (!validateForm()) {
      return
    }
    try {
      const resInfo = await audioService.graphicCreationStore({
        graphic_creation_no: '',
        officalAccountOrientation: formInfo.officalAccountOrientation,
        pictureType: Number(formInfo.pictureType),
        pictureStyle: Number(formInfo.pictureStyle),
        keywords: formInfo.content,
      })
      await useGraphicStore.getState().getBroadcastDetail(resInfo.id + '')
      commit(resInfo)
    } catch (error) {
      console.error('🚀 ~ handleSubmit ~ error:', error)
      setFormErrors((prev) => ({
        ...prev,
        submit: '提交失败，请重试',
      }))
    }
  }

  const handleUpdatePicture = (item: any) => {
    console.log('item:', item)
    useGraphicStore.getState().getGraphicPictureDetail({
      id: item.parentId,
      picture_id: item.id,
    })
  }
  const handleDownloadPicture = (item: any) => {
    // console.log('handleDownloadPicture item:', item)
    downloadFile(item.url)
  }

  return (
    <div className="flex flex-row w-full items-start gap-8 p-4 pt-0">
      <div className="w-96 space-y-4">
        <div className="w-full flex flex-col bg-white/10 p-4 rounded-lg border border-[#B9AEFF]/10">
          <div className="text-white/80">Content</div>
          <div className="flex-1 flex flex-col pl-1 pr-1 space-y-4 pt-3 pb-5 overflow-y-auto my-scrollbar">
            {formErrors.submit && (
              <Alert variant="destructive">
                <AlertDescription>{formErrors.submit}</AlertDescription>
              </Alert>
            )}
            <div className="w-full">
              <textarea
                value={formInfo.content}
                onChange={(e) => {
                  setFormInfo({ ...formInfo, content: e.target.value })
                  clearError('content')
                }}
                className={cn(
                  'my-scrollbar w-full h-[120px] bg-black/40 p-2 text-sm placeholder:text-white/40 border border-transparent focus:border-white outline-none text-white/80 rounded-[10px] resize-none',
                  formErrors.content && 'border-red-500',
                )}
                placeholder="Please enter the key information for the copy"
              />
              {formErrors.content && (
                <div className="mt-1 text-sm text-red-500">{formErrors.content}</div>
              )}
            </div>
            <div className="w-full flex gap-4">
              <div className="flex-1">
                <Select
                  value={formInfo.officalAccountOrientation}
                  onValueChange={(value) => {
                    setFormInfo({ ...formInfo, officalAccountOrientation: value })
                    clearError('officalAccountOrientation')
                  }}
                >
                  <SelectTrigger
                    className={cn(
                      'h-7 rounded-[10px] text-white/40',
                      formErrors.officalAccountOrientation && 'border-red-500',
                    )}
                  >
                    <SelectValue placeholder="Profiling" />
                  </SelectTrigger>
                  <SelectContent>
                    {systemConfig.officalAccountOrientation.map((item) => (
                      <SelectItem key={item.value} value={item.value}>
                        {item.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formErrors.pictureType && (
                  <div className="mt-1 text-sm text-red-500">
                    {formErrors.pictureType}
                  </div>
                )}
              </div>

              <div className="flex-1">
                <Select
                  value={formInfo.pictureType}
                  onValueChange={(value) => {
                    setFormInfo({ ...formInfo, pictureType: value })
                    clearError('pictureType')
                  }}
                >
                  <SelectTrigger
                    className={cn(
                      'h-7 rounded-[10px] text-white/40',
                      formErrors.pictureType && 'border-red-500',
                    )}
                  >
                    <SelectValue placeholder="Type" />
                  </SelectTrigger>
                  <SelectContent>
                    {systemConfig.pictureType.map((item) => (
                      <SelectItem key={item.value} value={item.value}>
                        {item.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formErrors.officalAccountOrientation && (
                  <div className="mt-1 text-sm text-red-500">
                    {formErrors.officalAccountOrientation}
                  </div>
                )}
              </div>

              <div className="flex-1">
                <Select
                  value={formInfo.pictureStyle}
                  onValueChange={(value) => {
                    setFormInfo({ ...formInfo, pictureStyle: value })
                    clearError('pictureStyle')
                  }}
                >
                  <SelectTrigger
                    className={cn(
                      'h-7 rounded-[10px] text-white/40',
                      formErrors.pictureStyle && 'border-red-500',
                    )}
                  >
                    <SelectValue placeholder="style" />
                  </SelectTrigger>
                  <SelectContent>
                    {systemConfig.pictureStyle.map((item) => (
                      <SelectItem key={item.value} value={item.value}>
                        {item.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formErrors.pictureStyle && (
                  <div className="mt-1 text-sm text-red-500">
                    {formErrors.pictureStyle}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="flex justify-center items-center w-full px-4">
            <Button
              className="w-full h-11 rounded-full bg-[#A091FD]"
              onClick={handleSubmit}
            >
              Generate
            </Button>
          </div>
        </div>
        <div className="w-full">{children}</div>
      </div>
      <div className="flex-1 flex h-full flex-wrap gap-4 bg-white/10 p-4 rounded-lg border border-[#B9AEFF]/10">
        {[0, 1, 2, 3].map((index) => {
          const item = pictureList[index]
          return (
            <Card
              key={index}
              className="relative flex-1 min-w-[calc(50%-1rem)] border-none"
            >
              <CardContent className="p-0 h-full">
                <div className="relative overflow-hidden bg-black/40 rounded-lg">
                  <div className="absolute top-0 left-0 right-0 bottom-0 flex justify-center items-center">
                    {/* <img
                        src="/img/preview-image.png"
                        alt="placeholder"
                        className="max-w-full max-h-full object-cover"
                      /> */}
                    {item?.url && (
                      <img
                        src={item.url}
                        alt="placeholder"
                        className="cursor-pointer max-w-full max-h-full object-cover"
                        onClick={() => {
                          handlePreview({
                            title: 'Preview image',
                            url: item.url,
                            type: 'image',
                          })
                        }}
                      />
                    )}
                  </div>
                </div>
                <div className="absolute bottom-2 left-2 right-2 flex justify-between">
                  {item && (
                    <>
                      <Button
                        variant="outline"
                        size="sm"
                        className="h-[30px]"
                        onClick={() => {
                          handleUpdatePicture(item)
                        }}
                      >
                        Update
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        className="h-[30px]"
                        onClick={() => {
                          handleDownloadPicture(item)
                        }}
                      >
                        Download
                      </Button>
                    </>
                  )}
                </div>
              </CardContent>
            </Card>
          )
        })}
      </div>
      <div className="w-40"></div>
    </div>
  )
}

export default PhotoUploadLayout
